import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:memo/state/model/todo.dart';
import 'package:memo/state/work_record_state.dart';
import 'package:memo/widget/todo_item_widget.dart';
import 'package:provider/provider.dart';

class HistoryTodoListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Consumer<WorkRecordState>(builder: (context, state, _) {
          return InkWell(
            child: Row(
              children: <Widget>[
                Text("${DateFormat("yyyy-MM-dd").format(state.dateTime)}"),
                const SizedBox(width: 3.0),
                const Icon(Icons.date_range)
              ],
            ),
            onTap: () => _selectDate(context, state, state.dateTime),
          );
        }),
      ),
      body: Consumer<WorkRecordState>(builder: (context, state, _) {
        return FutureBuilder<List<Todo>>(initialData: [], builder: (context, snapshot) {
          return ListView.builder(
              itemBuilder: (context, index) {
                final item = snapshot.data[index];
                return TodoItemWidget(
                  key: Key(item.id),
                  todo: item,
                  onLongPress: () => _onLongPress(context, state, item),
                );
              },
              itemCount: snapshot.data.length);
        }, future: state.queryTodo(state.dateTime),);
      }),
    );
  }

  Future<void> _selectDate(
      BuildContext context, WorkRecordState state, DateTime dateTime) async {
    final date = await showDatePicker(
      context: context,
      initialDate: dateTime,
      firstDate: dateTime.add(Duration(days: -90)),
      lastDate: DateTime.now(),
    );
    if (date != null) {
      state.dateTime = date;
    }
  }

  Future<void> _onLongPress(
      BuildContext context, WorkRecordState state, Todo todo) async {
    bool flag = await deleteDialog(context);
    if (flag) {
      await state.delete(todo);
    }
  }
}
